const cloud = require('wx-server-sdk')
cloud.init({
  env: "env-8gmua3du524302b0"
})
const db = cloud.database()
exports.main = async (event, context) => {


  const wxContext = cloud.getWXContext()
  var res = ""
  switch (event.type) {
    case "push_information":
      try {
        const result = await cloud.openapi.templateMessage.send({
            touser: 'OPENID',
            page: 'index',
            data: {
              keyword1: {
                value: '339208499'
              },
              keyword2: {
                value: '2015年01月05日 12:30'
              },
              keyword3: {
                value: '腾讯微信总部'
              },
              keyword4: {
                value: '广州市海珠区新港中路397号'
              }
            },
            templateId: 'TEMPLATE_ID',
            formId: 'FORMID',
            emphasisKeyword: 'keyword1.DATA'
          })
        console.log(result)
        return result
      } catch (err) {
        console.log(err)
        return err
      }
      break
    case "getDefaultValue":
      var res = await db.collection("default_value").where(event.where).get()
      var user = await db.collection("user").where({
        "openId": wxContext.OPENID
      }).get()
      return {
        openid: wxContext.OPENID,
          appid: wxContext.APPID,
          unionid: wxContext.UNIONID,
          env: wxContext.ENV,
          res,
          user
      }
      break
    case "update_user_info":
      var res = await db.collection("user").where({
        "openId": wxContext.OPENID
      }).count()
      var user = null
      if (res.total > 0) {
        user = await db.collection("user").where({
          "openId": wxContext.OPENID
        }).update({
          "data": {
            "openId": wxContext.OPENID,
            "cardId": event.cardId,
            "department": event.department,
            "class": event.class,
            "studentId": event.studentId,
            "grade": event.grade,
            "year": event.year
          }
        })
      } else {
        user = await db.collection("user").add({
          "data": {
            "openId": wxContext.OPENID,
            "cardId": event.cardId,
            "department": event.department,
            "class": event.class,
            "studentId": event.studentId,
            "grade": event.grade,
            "isAdmin": false
          }
        })
      }
      return {
        openid: wxContext.OPENID,
          appid: wxContext.APPID,
          unionid: wxContext.UNIONID,
          env: wxContext.ENV,
          user
      }
      break
    case "getCourse":
      var user = await db.collection("user").where({
        "openId": wxContext.OPENID
      }).get()
      var res = user.data[0]
      var course_name = res.year + res.grade + res.class
      var course = await db.collection("course").where({
        "class": course_name
      }).get()
      return course
      break
    case "updateCourse":
      var user = await db.collection("user").where({
        "openId": wxContext.OPENID
      }).get()
      var res = user.data[0]
      var course_name = res.year + res.grade + res.class
      var course = await db.collection("course").where({
        "class": course_name
      }).get()
      event.data["class"] = course_name
      if (course.data.length > 0) {
        db.collection("course").where({
          "class": course_name
        }).update({
          data: event.data
        })
      } else {
        db.collection("course").add({
          data: event.data
        })
      }
      return ""
      break
    case "getEnv":
      var user = await db.collection("user").where({
        "openId": wxContext.OPENID
      }).get()
      return {
        openid: wxContext.OPENID,
          appid: wxContext.APPID,
          unionid: wxContext.UNIONID,
          env: wxContext.ENV,
          user
      }
      break
    case "addPosition":
      var res = await db.collection("position").add({
        data: {
          position: event.position
        }
      })
      return res
      break
    case "getPosition":
      return await db.collection("position").get()
      break
    case "getSeat":
      //1，已经预约，没到签到时间
      //2，没有预约，直接拉下来
      //3，已经预约，超出签到时间(小于当前时间-10分钟)，直接拉下来



      // var _ = db.command
      // var where = _.and({
      //   position_id: _.eq()
      // }, _.or([{
      //   isAppointment: false
      // }, {
      //   isAppointment: true,
      //   checkTime: _.lte(db.serverDate())//不知道有没有问题啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊
      // }]))
      return await db.collection("seat").where({
        position_id: event.position_id
      }).get()
      break
    case "add_seat":
      var res = await db.collection("seat").add({
        data: {
          seat: event.seat,
          position_id: event.position_id,
          isAppointment: false,
          check: false,
          checkTime: db.serverDate(),
          openId: ""
        }
      })
      return res
      break
    case "remove_seat":
      await db.collection("seat").doc(event._id).remove()
      return ""
      break
    case "changeSeat":
      await db.collection("seat").doc(event._id).update({
        data: event.data
      })
      return ""
      break
    case "remove_position":
      await db.collection("position").doc(event._id).remove()
      await db.collection("seat").where({
        position_id: event._id
      }).remove()
      return ""
      break
    case "appointment":
      await db.collection("seat").doc(event._id).update({
        data: {
          isAppointment: true,
          openId: wxContext.OPENID,
          check: false,
          checkTime: db.serverDate({
            offset: 10 * 60 * 1000
          }),
          position_id: event.position_id
        }
      })
      return ""
      break
    case "checkMyAppointment":
      var _ = db.command
      return await db.collection("seat").where(_.or([{
        openId: wxContext.OPENID,
        check: true
      }, {
        openId: wxContext.OPENID,
        isAppointment: true
      }, {
        openId: wxContext.OPENID,
        checkTime: _.gte(db.serverDate())
      }])).get()
      break
    case "signIn":
      return await db.collection("seat").doc(event.deskId).update({
        data: {
          check: true
        }
      })
      break
    case "signOut":
      return await db.collection("seat").where({
        openId: wxContext.OPENID,
        check: true        
      }).update({
        data: {
          openId: "",
          check: false,
          isAppointment:false
        }
      })

      break
    default:
      return {
        openid: wxContext.OPENID,
          appid: wxContext.APPID,
          unionid: wxContext.UNIONID,
          env: wxContext.ENV
      }
  }
}